<template>
    <div v-if="isAuth" class="official_account_graphics_container">
        <ZwSearchForm row-num="3" :option="searchOption" @search="search" @reset="reset" />
        <ZwTable
            ref="tableRef"
            class="table-box"
            tab-h="initial"
            :option="tableOption"
            :fetch-params="state.searchParams"
            :fetch-api="fetchApi()"
            empty-text="您还没有发布任何图文">
            <template #headerOperate>
                <div style="margin-right: 10px">
                    <el-button plain @click="toDraftbox">草稿箱</el-button>
                </div>
                <Dropdown :shwo-btn="['3']" @submit="toCreate">
                    <el-button type="primary">
                        新建图文
                        <el-icon class="el-icon--right">
                            <arrow-down />
                        </el-icon>
                    </el-button>
                </Dropdown>
            </template>
        </ZwTable>
    </div>
    <div v-else class="empty_box">
        <img class="empty_img" :src="emptyImage" alt="" />
        <div class="empty_title">您还没有授权任何公众号</div>
        <el-button size="small" type="primary" @click="toOfficialAccounts"> 去授权 </el-button>
    </div>
    <ZWGraphic ref="ZWGraphicRef" @submit="getGraphic" />
</template>

<script setup lang="tsx">
import emptyImage from '@/assets/noData.png';
import ArticleDetailItem from './components/ArticleDetailItem.vue';
import Dropdown from './components/Dropdown.vue';
import ZwSearchForm from '@/components/zw/search-form/SearchForm';
import ZwTable from '@/components/zw/table/Table';
import ZWGraphic from '@/components/ZWGraphic.vue';

import {
    officialSync,
    getOfficialArticleList,
    groupMassOffical,
    againSendMass
} from '@/api/content/channelFootage/officialaccountgraphics';
import { getOfficeAccountList } from '@/api/channelconfig/officeAccount';
import { ElMessage, ElImage, ElIcon, ElButton, ElTooltip } from 'element-plus';
import { Picture as IconPicture } from '@element-plus/icons-vue';
import { ref, reactive, computed, onMounted, onBeforeMount, onUnmounted } from 'vue';
import { useRouter, useRoute } from 'vue-router';
import { deepCopy } from '@/utils/helper';

const router = useRouter();
const defaultParams = {
    type: 2, //已发表的文章
    official_account_id: '', //公众号id
    article_title: '', //标题
    article_type: '', //1-单图文 2-多图文
    publish_time: [], // 发布时间
    publish_state: 0 //发布状态 0-全部 1-发布中 2-发布成功 3-发布失败
};
const state = reactive({
    searchParams: deepCopy(defaultParams),
    syncTime: '', // 最近更新时间
    searchHeight: '112px'
});

const tableRef: any = ref<HTMLElement | null>(null);

const searchOption = computed(() => {
    return [
        {
            label: '公众号',
            name: 'official_account_id',
            value: '',
            type: 'select',
            placeholder: '请选择公众号',
            fetchOptionApi: () => {
                return new Promise(resolve => {
                    const params = {
                        page: 1,
                        page_size: 100,
                        verify_type_info: 0
                    };
                    getOfficeAccountList(params).then(res => {
                        resolve(res.data);
                    });
                });
            },
            formatOption: (v: any) => ({
                label: v.nick_name,
                value: v.id
            })
        },
        {
            label: '标题',
            name: 'article_title',
            value: '',
            type: 'input',
            placeholder: '请输入标题或草稿标题进行搜索'
        },
        {
            label: '发布时间',
            name: 'publish_time',
            value: [],
            type: 'datePicker',
            datePickerType: 'daterange',
            datePickerFormat: 'YYYY-MM-DD HH:mm:ss',
            valueFormat: 'YYYY-MM-DD HH:mm:ss',
            defaultTime: [new Date(0, 0, 0, 0, 0, 0), new Date(0, 0, 0, 23, 59, 59)],
            startPlaceholder: '开始日期',
            endPlaceholder: '结束日期'
        },
        {
            label: '图文类型',
            name: 'article_type',
            value: '',
            type: 'select',
            placeholder: '请选择图文类型',
            fetchOptionApi: () => {
                return new Promise(resolve => {
                    resolve([
                        { name: '全部', id: '' },
                        { name: '单图文', id: 1 },
                        { name: '多图文', id: 2 }
                    ]);
                });
            },
            formatOption: (v: any) => ({
                label: v.name,
                value: v.id
            })
        },

        {
            label: '发布状态',
            name: 'publish_state',
            value: '',
            type: 'select',
            placeholder: '请选择图文状态',
            fetchOptionApi: () => {
                return new Promise(resolve => {
                    resolve([
                        { name: '全部', id: 0 },
                        { name: '已群发', id: 2 },
                        { name: '群发中', id: 1 },
                        { name: '群发失败', id: 3 }
                    ]);
                });
            },
            formatOption: (v: any) => ({
                label: v.name,
                value: v.id
            })
        }
    ];
});
const search = (v: any) => {
    state.searchParams = {
        ...deepCopy(defaultParams),
        ...v
    };
};
const reset = (v: any) => {
    state.searchParams = { ...deepCopy(defaultParams) };
};

// 表格
const tableOption = [
    {
        prop: 'publish_time',
        label: '发布日期',
        width: 200
    },
    {
        prop: 'draft_title',
        label: '草稿标题',
        width: 200
    },
    {
        prop: 'article_detail',
        label: '内容',
        minWidth: 200,
        render({ row, column, index }) {
            return <ArticleDetailItem list={row.article_detail} />;
        }
    },
    {
        prop: 'type_name',
        label: '图文类型',
        width: 200
        // render({ row }) {
        //   return row.type == 1 ? '单图文' : row.type == 2 ? '多图文' : ''
        // }
    },
    {
        prop: 'official',
        label: '公众号',
        minWidth: 200,
        render({ row }) {
            const slotError = (
                <ElIcon>
                    <IconPicture />
                </ElIcon>
            );
            return (
                <div class="official">
                    <ElImage
                        class="official_cover"
                        preview-src-list={[row.official_cover]}
                        preview-teleported={true}
                        fit="cover"
                        src={row.official_cover}
                        vSlots={{ error: slotError }}
                    />
                    <div class="official_name">{row.official_name}</div>
                </div>
            );
        }
    },
    {
        prop: 'publish_status_name',
        label: '群发状态',
        width: 120
        // render({ row }) {
        //   return row.type == 1 ? '单图文' : row.type == 2 ? '多图文' : ''
        // }
    },
    {
        prop: 'fail_reason',
        label: '失败原因',
        width: 150,
        render({ row }) {
            return (
                <>
                    <div vShow={row.fail_reason}>
                        <ElTooltip effect="dark" content={row.fail_reason}>
                            <p class="fail_reason">{row.fail_reason || '--'}</p>
                        </ElTooltip>
                    </div>
                    <span vShow={!row.fail_reason}>--</span>
                </>
            );
        }
    },
    {
        prop: 'operate',
        label: '操作',
        width: 200,
        fixed: 'right',
        isOperate: true,
        option: [
            {
                name: '重新群发',
                click: (row: any) => anewSend(row),
                isRender: ({ row }: any) => row.publish_status === 3
            },
            {
                name: '重新编辑',
                click: (row: any) => anewEdit(row),
                isRender: ({ row }: any) => row.publish_status === 3
            },
            {
                name: '复制草稿',
                click: (row: any) => copyDraft(row),
                isRender: ({ row }: any) => row.publish_status === 2
            }
        ]
    }
];
const fetchApi = () => {
    return getOfficialArticleList;
};
// 刷新表格
const reloadTable = () => {
    tableRef.value.reload();
};
const ZWGraphicRef = ref<any>(null);
// 去草稿箱
const toDraftbox = () => {
    router.push('/content/channelFootage/officialaccountgraphics/draftbox');
};
// 新建图文
const toCreate = (imgTextType: string) => {
    if (imgTextType == '1') {
        ZWGraphicRef.value.appDialog.multiple = false;
        ZWGraphicRef.value.appDialog.visible = true;
    } else {
        router.push({ path: '/content/channelFootage/officialaccountgraphics/detail', query: { imgTextType } });
    }
};
// 已有图文确认
const getGraphic = (v: any) => {
    router.push({
        path: '/content/channelFootage/officialaccountgraphics/detail',
        query: { imgTextType: v[0].article_detail[0].type, ID: v[0].id }
    });
};
// 重新发送
const anewSend = async (row: any) => {
    try {
        await againSendMass({ id: row.id, type: 2 });
        ElImage.success('发送成功');
    } finally {
        reloadTable();
    }
};
// 重新编辑
const anewEdit = (row: any) => {
    const query = {
        imgTextType: row.detail_type,
        type: 'edit',
        ID: row.id,
        id: row.id,
        copy: 2
    };
    router.push({ path: '/content/channelFootage/officialaccountgraphics/detail', query });
};
// 复制草稿
const copyDraft = (row: any) => {
    router.push({
        path: '/content/channelFootage/officialaccountgraphics/detail',
        query: { imgTextType: row.detail_type, ID: row.id, id: row.id, copy: 2 }
    });
};

const toOfficialAccounts = () => {
    router.push('/channelconfig/officeAccount/oaManage');
};
// 是否有授权公众号
const isAuth = ref(false);
onMounted(() => {
    getOfficeAccountList({ page: 1, page_size: 100, verify_type_info: 0 }).then(res => {
        if (res.data?.length > 0) {
            isAuth.value = true;
        }
    });
});
const timer = setTimeout(() => {
    ElMessage.closeAll();
}, 1000 * 3);
onUnmounted(() => {
    clearTimeout(timer);
});
</script>

<style lang="scss" scoped>
.empty_box {
    height: calc(100vh - 150px);
    background: #fff;
    display: flex;
    justify-content: center;
    align-items: center;
    flex-direction: column;

    .empty_img {
        transform: translateX(15%);
    }

    .empty_title {
        margin-bottom: 23px;
        font-size: 14px;
        font-family: PingFangSC-Regular, 'PingFang SC';
        font-weight: 400;
        color: #969696;
    }
}

.create_btn {
    display: flex;
    align-items: center;

    &::before {
        content: '';
        display: inline-block;
        width: 16px;
        height: 16px;
        background: url('@/assets/content/channelFootage/officialaccountgraphics/xintuwen.png') no-repeat;
        background-size: 100% 100%;
        margin-right: 5px;
    }

    &:hover::before {
        background: url('@/assets/content/channelFootage/officialaccountgraphics/xintuwen_active.png') no-repeat;
    }
}

.yiyoutuwen {
    &::before {
        background: url('@/assets/content/channelFootage/officialaccountgraphics/yiyoutuwen.png') no-repeat;
    }

    &:hover::before {
        background: url('@/assets/content/channelFootage/officialaccountgraphics/yiyoutuwen_active.png') no-repeat;
    }
}

.text {
    &::before {
        background: url('@/assets/content/channelFootage/officialaccountgraphics/text.png') no-repeat;
    }

    &:hover::before {
        background: url('@/assets/content/channelFootage/officialaccountgraphics/text_active.png') no-repeat;
    }
}

.official_account_graphics_container {
    height: calc(100vh - 142px);
    padding: 24px;
    border: 1px solid #eaeaea;
    border-radius: 4px;
    box-sizing: border-box;
    background-color: #fff;
    display: flex;
    flex-direction: column;
    overflow: hidden;

    .zw-table {
        display: flex;
        flex-direction: column;
        flex: 1;
        overflow: hidden;

        :deep(.el-table) {
            flex: 1;

            .el-table__empty-block {
                position: absolute;
                top: 50%;
                left: 50%;
                transform: translate(-50%, -50%);
            }
        }
    }

    :deep(.article_detail) {
        display: flex;
        align-items: center;
        margin-bottom: 5px;

        .article_cover {
            min-width: 30px;
            max-width: 30px;
            min-height: 30px;
            max-height: 30px;
            margin-right: 10px;
            font-size: 30px;
        }

        .article_title {
            font-size: 14px;
            font-weight: 300;
            color: #33302d;

            &:hover {
                color: #ff6b00;
            }
        }
    }

    :deep(.official) {
        display: flex;
        align-items: center;

        .official_cover {
            min-width: 30px;
            max-width: 30px;
            min-height: 30px;
            max-height: 30px;
            margin-right: 10px;
            border-radius: 50%;
            font-size: 25px;
            display: grid;
            place-items: center;
        }

        .official_name {
            font-size: 14px;
            font-weight: 300;
            color: #33302d;
        }
    }
}

:deep(.fail_reason) {
    width: 100px;
    text-overflow: ellipsis;
    white-space: nowrap;
    overflow: hidden;
}
</style>
